package api

import (
	"FeedXmh/app/dao"
	"FeedXmh/app/model"

	"fmt"
	"github.com/gogf/gf/database/gdb"
	"github.com/gogf/gf/encoding/gjson"
	"github.com/gogf/gf/encoding/gparser"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/os/gtime"
	"github.com/silenceper/wechat/v2/officialaccount/message"
	"time"
)

type wechatAPI struct {
}

var WechatAPI wechatAPI

const (
	AlarmTypeHappen int = 1
	AlarmTypeCancel int = 0
)

func (*wechatAPI) Index(r *ghttp.Request) {
	officialAccount := model.GlobalOfficialAccount
	// 传入request和responseWriter
	server := officialAccount.GetServer(r.Request,r.Response.ResponseWriter)
	user:=officialAccount.GetUser()
	accessToken,_:=officialAccount.GetAccessToken()
	g.Log().Line().Debugf("access_token:%s", accessToken)
	//设置接收消息的处理方法
	server.SetMessageHandler(func (msg *message.MixMessage) *message.Reply {
		openid:=msg.GetOpenID()
		g.Log().Line().Debugf("OpenID:%s",openid)
		userInfo,err:= user.GetUserInfo(openid)
		if err!=nil{
			g.Log().Line().Error(err)
		}
		if userInfo!=nil{
			g.Log().Line().Debug(userInfo)
		}

		var reply message.Reply
		if msg.MsgType == message.MsgTypeText{
			//回复消息：演示回复用户发送的消息
			text := message.NewText(msg.Content)
			reply.MsgType = message.MsgTypeText
			reply.MsgData = text
			//&message.Reply{MsgType: message.MsgTypeText, MsgData: text}

		}else if msg.MsgType == message.MsgTypeEvent{
			if msg.Event == message.EventSubscribe{
				g.Log().Line().Debugf("openid:%s Subscribe",openid)

				exist,err:=dao.T_wx_oa_account.ExistOpenId(openid)
				if err!=nil{
					g.Log().Line().Error(err)
				}else{
					if !exist{
						oa_user:=officialAccount.GetUser()
						userinfo,err:= oa_user.GetUserInfo(openid)
						if err!=nil{
							g.Log().Line().Error(err)
						}else{
							now:=gtime.Now().String()
							item:=gdb.Map{
								"openid":userinfo.OpenID,
								"unionid":userinfo.UnionID,
								"update_date":now,
								"subscribe":userinfo.Subscribe,
								"subscribe_time":gtime.NewFromTimeStamp(int64(userinfo.SubscribeTime)).String(),
								"subscribe_scene":userinfo.SubscribeScene,
							}
							isOk,err:= dao.T_wx_oa_account.Save(item)
							if !isOk {
								g.Log().Line(true).Error(err.Error())
							}else{
								g.Log().Line(true).Debugf("save t_wx_oa_account ok,openid:%s,unionid:%s",userinfo.OpenID,userinfo.UnionID)
							}
						}
					}else{
						g.Log().Line().Debugf("openid:%s exist",openid)
					}
				}
			}else if msg.Event == message.EventUnsubscribe{
				g.Log().Line().Debugf("openid:%s Unsubscribe",openid)
				//dao.T_wx_oa_account.Delete(" openid=%s")
			}
		}
		return &reply
	})
	//处理消息接收以及回复
	err := server.Serve()
	if err != nil {
		fmt.Println(err)
		return
	}
	//发送回复的消息
	server.Send()
}

func (*wechatAPI) SyncAccount(r *ghttp.Request) {
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  "",
		"count": "",
	}
	code,msg:=WechatAPI.WxSyncAccount()
	res["code"]=code
	res["msg"]=msg
	r.Response.WriteJson(res)
	r.ExitAll()
}


func (*wechatAPI) TestHappen(r *ghttp.Request){
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  "",
		"count": "",
	}

	openid:=r.GetFormString("openid")
	code,msg,err:= WechatAPI.WxSendNotice(openid,fmt.Sprintf("[%s]有新的设备告警","测试养殖场"),"测试设备","测试栏舍","告警测试内容","","2022-06-20 10:10:10","请及时排查处理！",AlarmTypeHappen)
	if err!=nil{
		res["code"]=code
		res["msg"]=err.Error()
	}else{
		res["code"]=code
		res["msg"]=msg
	}

	r.Response.WriteJson(res)
	r.ExitAll()
}

func (*wechatAPI) TestCancel(r *ghttp.Request){
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  "",
		"count": "",
	}

	openid:=r.GetFormString("openid")
	code,msg,err:= WechatAPI.WxSendNotice(openid,fmt.Sprintf("[%s]设备告警消除通知","测试养殖场"),"测试设备","测试栏舍","告警测试内容","","2022-06-01 10:00:00","消除时间为2022-06-14 09:49:51，历时5天22时6分28秒",AlarmTypeCancel)
	if err!=nil{
		res["code"]=code
		res["msg"]=err.Error()
	}else{
		res["code"]=code
		res["msg"]=msg
	}

	r.Response.WriteJson(res)
	r.ExitAll()
}




func (*wechatAPI) WxSyncAccount() (code int,msg string) {
	oa := model.GlobalOfficialAccount
	oa_user:=oa.GetUser()

	openids,err:= oa_user.ListAllUserOpenIDs()
	//var list []*user.Info
	//var needAddList gdb.List
	num:=0
	if err!=nil{
		g.Log().Line().Error(err)
		code=-1
		msg=err.Error()
	}else{
		if len(openids)>0{
			g.Log().Line().Debug(openids)
			for _,openid:=range openids{
				exist,err:= dao.T_wx_oa_account.ExistOpenId(openid)
				if err!=nil{
					g.Log().Line().Error(err)
					continue
				}
				if !exist{

					userinfo,err:= oa_user.GetUserInfo(openid)
					if err!=nil{
						g.Log().Line().Error(err)
						break
					}else{
						//list = append(list, userinfo)
						now:=gtime.Now().String()
						item:=gdb.Map{
							"openid":userinfo.OpenID,
							"unionid":userinfo.UnionID,
							"update_date":now,
							"subscribe":userinfo.Subscribe,
							"subscribe_time":gtime.NewFromTimeStamp(int64(userinfo.SubscribeTime)).String(),
							"subscribe_scene":userinfo.SubscribeScene,
						}
						isOk,err:= dao.T_wx_oa_account.Save(item)
						if !isOk {
							g.Log().Line(true).Error(err.Error())
						}else{
							g.Log().Line(true).Debugf("save t_wx_oa_account ok,openid:%s,unionid:%s",userinfo.OpenID,userinfo.UnionID)
							num++
						}
					}
				}
			}


			code=0
			msg =fmt.Sprintf("sync %d to t_wx_oa_account ok",num)
		}else{
			g.Log().Line().Debug("获取不到公众号用户openids")
			code=-2
			msg="获取不到公众号用户openids"
		}
	}
	return code,msg
}


func (*wechatAPI) WxSendNotice(openid string, first string,keyword1 string,keyword2 string,keyword3 string,keyword4 string,keyword5 string,remark string,alarmType int) (code int,msg string,err error){
	officialAccount := model.GlobalOfficialAccount
	accessToken,_:=officialAccount.GetAccessToken()
	TemplateUrl:=g.Cfg().GetString("wechat.TemplateUrl")+accessToken
	AlarmTemplateID:=g.Cfg().GetString("wechat.AlarmTemplateID")
	var body string

	var color string
	if alarmType==AlarmTypeHappen{
		color = g.Cfg().GetString("wechat.AlarmHappenColor")
	}else{
		color = g.Cfg().GetString("wechat.AlarmCancelColor")
	}


	data:=g.Map{
		"touser":openid,
		"template_id":AlarmTemplateID,
		"data":g.Map{
			"first":g.Map{
				"value":first,
				"color":color,
			},"keyword1":g.Map{
				"value": keyword1,
				"color": color,
			},"keyword2":g.Map{
				"value":keyword2,
				"color":color,
			},"keyword3":g.Map{
				"value":keyword3,
				"color":color,
			},"keyword4":g.Map{
				"value":keyword4,
				"color":color,
			},"keyword5":g.Map{
				"value":keyword5,
				"color":color,
			},"remark":g.Map{
				"value":remark,
				"color":color,
			},
		},
	}
	body,_=gparser.VarToJsonString(data)

	client:=ghttp.NewClient()
	client.Timeout(20 * time.Second)
	resp,error :=client.Post(TemplateUrl,body)


	if error!=nil{
		g.Log().Line().Error(err)
		code=-1
		msg=err.Error()
		err = error
	}else{
		respStr:=resp.ReadAllString()
		g.Log().Line().Debug(respStr)
		if json, error1 := gjson.DecodeToJson(respStr); error1 == nil {
			errcode:=json.GetInt("errcode")
			errmsg:=json.GetString("errmsg")
			code=errcode
			msg=errmsg
		}else{
			g.Log().Line().Error(err)
			code=-2
			msg=err.Error()
			err = error1
		}
	}

	return code,msg,err
}





